import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Ref;

/**
 * @author zhangshuai
 * @version V1.0
 * @Project Java2_26
 * @Package PACKAGE_NAME
 * @Description:
 * @Date 2025/5/19 17:01
 */

public class RefjectTest {
    //反射：是一种机制，是指jvm运行期可以动态的获取或者是改变类的所有信息，包括创建对象，属性，方法，构造方法，都可以获取，改变

    //有3种方式得到一个Class类对象，类的模板，类的实体
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        // 通过类名获取Class对象
        Class<?> aClass = Class.forName("RefjectTest");
        // 通过类对象获取Class对象
        Class<RefjectTest> aClass1 = RefjectTest.class;
        // 通过对象获取Class对象
        Class<? extends RefjectTest> aClass2 = new RefjectTest().getClass();

        //根据类对象，创建对象，获取属性，获取方法，修改属性
        RefjectTest o = (RefjectTest) aClass.newInstance();
        o.setAge(11);
        o.setName("水岸东方");
        System.out.println(o);
        //有参构造创建对象
        RefjectTest declaredo = (RefjectTest) aClass.getDeclaredConstructor(String.class, int.class).newInstance("士大夫", 13);
        System.out.println(declaredo);

        //访问，调用方法 name (方法名)
        Method setAge = aClass1.getDeclaredMethod("setAge",int.class);
        System.out.println(setAge);
       setAge.invoke(declaredo,15);
        System.out.println(declaredo);
        Method setName = aClass1.getDeclaredMethod("setName",String.class);
        System.out.println(setName);
        setName.invoke(declaredo,"张三");
        System.out.println(declaredo);


        //访问属性，修改属性
        Field name1 = aClass2.getDeclaredField("name");
        Field age1 = aClass2.getDeclaredField("age");
        name1.setAccessible(true); //解除写的限制
        name1.set(declaredo,"李四");
        age1.setAccessible(true);
        age1.set(declaredo,50);
        System.out.println(declaredo.getAge()+ declaredo.getName());




    }

    private String name;
    private int age;

    public RefjectTest() {
    }

    public RefjectTest(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "RefjectTest{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}